<?php

/**
 * 启动图管理
 *
 * @author suning <snsnsky@gmail.com>
 */

use MobileApi\AppInfo;
use Common\Bridge;
use Common\Upload;
use Common\ResourcePathManager;
use Common\PhotoImage;

define('SITE_AUTH', 'mobile-app-screen');
require('../../../common.inc.php');

class screenimage extends \lib\core\AdminAction
{
    private $appinfo = [];

    public function __construct()
    {
        global $app;
        parent::__construct($app);

        $this->appinfo = loadconf('mobileapi/base');
    }

    /**
     * 首页
     */
    public function doDefault()
    {
        $smarty = $this->app->page();

        $page = max(1, intval($_GET['page']));

        $appid_ios = intval(MOBILE_APPID_IPHONE);
        $appid_adr = intval(MOBILE_APPID_ANDROID);

        $pdo = Bridge::pdo(Bridge::DB_MOBILE_R);
        $query = $pdo->prepare("select count(Id) from `AppScreenImage` where Status=1 and AppId in (:appid_ios,:appid_adr)");
        $query->bindValue(':appid_ios', $appid_ios);
        $query->bindValue(':appid_adr', $appid_adr);
        $query->execute();
        $total = $query->fetchColumn();

        if ($total > 0) {
            $offset = ($page - 1) * self::PAGE_SIZE;
            $pagesize = self::PAGE_SIZE;

            $query = $pdo->prepare("select * from `AppScreenImage` where Status=1  and AppId in (:appid_ios,:appid_adr) order by Id desc limit $offset,$pagesize");
            $query->bindValue(':appid_ios', $appid_ios);
            $query->bindValue(':appid_adr', $appid_adr);
            $query->execute();
            $data = $query->fetchAll();

            if (!empty($data)) {
                $now = time();
                foreach ($data as $key => $value) {
                    if (strtotime($value['StartTime']) > $now) {
                        // 未开始
                        $data[$key]['StartStatus'] = 1;
                    } elseif (strtotime($value['EndTime']) < $now) {
                        // 已结束
                        $data[$key]['StartStatus'] = 3;
                    } else {
                        // 正在进行中
                        $data[$key]['StartStatus'] = 2;
                    }
                }
            }
            $smarty->value('data', $data);

            $pagination = $this->pagination($total, self::PAGE_SIZE, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('app_ids', $this->appinfo);
        $smarty->output();
    }

    /**
     * 添加入口
     */
    public function doAdd()
    {
        if (isset($_POST['app_id'])) {
            $appid = intval($_POST['app_id']);
            $name = trim($_POST['name']);
            $url = trim($_POST['url']);
            $description = trim($_POST['description']);
            $starttime = trim($_POST['start_time']);
            $endtime = trim($_POST['end_time']);

            if (!isset($this->appinfo[$appid])) {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => '请选择应用名！']);
            } elseif (empty($name) || empty($description) || empty($starttime) || empty($endtime)) {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => '字段填写不完整']);
            } elseif (strtotime($starttime) > strtotime($endtime)) {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => '启动图显示开始时间不能大于结束时间！']);
            }

            if (!isset($_FILES['appscreen']['name']) || $_FILES['appscreen']['error'] != 0) {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => '图片上传失败!']);
            }

            //添加限制
            $rel = PhotoImage::checkImage($_FILES['appscreen'],375,512,0);
            if(!empty($rel['code'])){
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => $rel['msg']]);
            }
            // 上传图片
            $img_url = self::saveImageUrl($_FILES['appscreen']['tmp_name']);
            if (empty($img_url)) {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => '图片上传到oss失败!']);
            }
            // 数据入库
            $now = date('Y-m-d H:i:s');
            $data = [
                'AppId' => $appid,
                'Name' => $name,
                'ImgUrl' => $img_url,
                'Url' => $url,
                'Channel' => '',
                'Description' => $description,
                'StartTime' => $starttime,
                'EndTime' => $endtime,
                'CreateTime' => $now,
                'LastTime' => $now,
                'Status' => 1
            ];
            $pdo_w = Bridge::pdo(Bridge::DB_MOBILE_W);
            if ($pdo_w->insert('AppScreenImage', $data)) {
                $id = $pdo_w->lastInsertId();

                // 删除缓存
                AppInfo::removeCache(AppInfo::CACHE_APP_SCREEN, $appid);

                $this->adminLog('添加启动图', $id, 'add', serialize($data));
                HDshowMsg('添加成功！', ['type' => 'success', 'desc' => "", 'url' => 'data/modules/mobile/screenimage.php']);
            } else {
                HDshowMsg('添加失败！', ['type' => 'error', 'desc' => "请稍后重试！"]);
            }
        } else {
            $smarty = $this->app->page();
            $smarty->value('app_ids', $this->appinfo);
            $smarty->output('mobile/screenimage_add.tpl');
        }
    }

    /**
     * 删除入口
     */
    public function doDelete()
    {
        $id = intval($_GET['id']);
        $app_id = intval($_GET['app_id']);
        if (!$id || !isset($this->appinfo[$app_id])) {
            HDshowMsg('删除失败', ['type' => 'error', 'desc' => '参数非法！']);
        }

        $pdo_w = Bridge::pdo(Bridge::DB_MOBILE_W);
        $where = ['Id' => $id, 'AppId' => $app_id];
        $data = ['Status' => 2];

        if ($pdo_w->update('AppScreenImage', $data, $where)) {
            AppInfo::removeCache(AppInfo::CACHE_APP_SCREEN, $app_id);
            $this->adminLog('删除启动图', $id, 'update', serialize($data));
            HDshowMsg('删除成功！');
        } else {
            HDshowMsg('删除失败', ['type' => 'error', 'desc' => '请稍后再试！']);
        }
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($filename)
    {
        ///
        $upload_dir = \Common\ResourcePathManager::getScreenSavePath();
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $id = $msectime;

        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }

        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{id}.jpg'
                ],
            ],
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                return "http://img.jinguonet.com/screen/" . $id . ".jpg?v=" . time();
            }


        }

        return false;
    }
}

$app->run();
